<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>注册</title>
  <style>
    *{margin: 0;padding: 0;}
    *{box-sizing: border-box;}
    body{
      border: 1px solid red;
      min-height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }
    .form-wrapper{
      padding: 20px;
      border: 1px solid #ddd;
      min-width: 350px;
    }
    .form-wrapper .row{
      margin: 10px 0;
    }
    .form-wrapper .row>label{
      display: inline-block;
      min-width: 4em;
    }

  </style>
</head>
<body>
  <div class="form-wrapper">
    <h1>注册</h1>
    <form id="signUpForm">
      <div class="row">
        <label>邮箱</label>
        <input type="text" name="email">
        <span class="error"></span>
      </div>
      <div class="row">
        <label>密码</label>
        <input type="password" name="password">
        <span class="error"></span>
      </div>
      <div class="row">
        <label>确认密码</label>
        <input type="password" name="password_confirmation">
        <span class="error"></span>
      </div>
      <div class="row">
        <input type="submit" value="注册">
      </div>
    </form>
  </div>
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  <script>
    let $form = $('#signUpForm')
    $form.on('submit', (e)=>{
      e.preventDefault()
      let hash = {}
      let need = ['email', 'password', 'password_confirmation'] //查找到name为email、password的元素
      need.forEach((name)=>{ 
        let value = $form.find(`[name=${name}]`).val() //获取用户输入的值
        hash[name] = value           //然后把这个值放到这个hsah里，就是email等于用户输入的email的值
      })
      $form.find('.error').each((index, span)=>{    //初始是找到所有的.error把他们设为空
        $(span).text('')
      })
      if(hash['email'] === ''){            //验证这个hash
        $form.find('[name="email"]').siblings('.error')
          .text('填邮箱呀同学')
        return
      }
      if(hash['password'] === ''){
        $form.find('[name="password"]').siblings('.error')
          .text('填密码呀同学')
        return
      }
      if(hash['password_confirmation'] === ''){
        $form.find('[name="password_confirmation"]').siblings('.error')
          .text('确认密码呀同学')
        return
      }
      if(hash['password'] !== hash['password_confirmation']){
        $form.find('[name="password_confirmation"]').siblings('.error')
          .text('密码不匹配')
        return
      }
      $.post('/sign_up', hash)   //用ajax 路径是sign_up  内容是hash
        .then((response)=>{     //用到了promise 成功了打这个
          console.log(response)
        }, (request)=>{     //失败了打这个
          let {errors} = request.responseJSON
          if(errors.email && errors.email === 'invalid'){ //如果这个email存在而且这个email等于invalid
            $form.find('[name="email"]').siblings('.error')  
              .text('邮箱格式错误')
          }
        })
    })
  </script>
</body>
</html>
